    //
//  ReadViewController.m
//  OrderOnline
//
//  Created by YAPPA_3 on 11/29/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//



#import "ReadViewController.h"
#import "DataManager.h"
#import "OrderOnlineViewController.h"

#define kHeightLand 660
#define kWidthLand 1024
#define kHeightPort 916
#define kWidthPort 768



@implementation ReadViewController
@synthesize m_scrollView;
@synthesize m_naviBar;
@synthesize m_barButonSlide;
@synthesize m_barAdd;
@synthesize m_toolBar;
@synthesize m_viewInfo;
@synthesize m_lblName;
@synthesize m_lblPrice;
@synthesize m_lblDiscount;
@synthesize m_titleName;
@synthesize m_titlePrice;
@synthesize m_titleDiscount;
@synthesize m_popover = popover;
@synthesize m_popoverViewController = popoverViewController;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.		
		m_listImageData = [[NSMutableArray alloc] init];
		m_listData = [[NSMutableArray alloc] init];
		m_listImageView = [[NSMutableArray alloc] init];
		m_typeMenu = [OrderOnlineViewController Shared].m_typeMenu;
		m_isInfoHide = YES;
		[self loadImageData];
		
	}
    return self;
}

- (void) loadImageData
{
	SAFE_RELEASE(m_listImageData)
	m_listImageData = [[NSMutableArray alloc] init];
	SAFE_RELEASE(m_listData)
	m_listData = [[NSMutableArray alloc] init];
	NSMutableArray* listFood = [DataManager Shared].m_XmlParser.m_menuFood.m_listFood;
	if (m_typeMenu == TYPE_MENU_ALL) {
		for (Food* food in listFood) {		
			NSString* imagePath = [[NSBundle mainBundle] pathForResource:food.m_linkImage ofType:@"jpg"];
			UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
			if (image != nil) {
				[m_listImageData addObject:image];	
				[m_listData addObject:food];
			}
			
		}
	}
	if (m_typeMenu == TYPE_MENU_FOOD) {
		for (Food* food in listFood) {	
			if ([food.m_type isEqualToString:@"food"]) {
				NSString* imagePath = [[NSBundle mainBundle] pathForResource:food.m_linkImage ofType:@"jpg"];
				UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
				if (image != nil) {
					[m_listImageData addObject:image];
					[m_listData addObject:food];
				}
				
			}
					
		}
	}
	if (m_typeMenu == TYPE_MENU_DRINK) {
		for (Food* food in listFood) {	
			if ([food.m_type isEqualToString:@"drink"]) {
				NSString* imagePath = [[NSBundle mainBundle] pathForResource:food.m_linkImage ofType:@"jpg"];
				UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
				if (image != nil) {
					[m_listImageData addObject:image];
					[m_listData addObject:food];
				}
				
			}
			
		}
	}
	
}

- (void) loadImageView: (BOOL) isLand
{
	SAFE_RELEASE(m_listImageView)
	m_listImageView = [[NSMutableArray alloc] init];		
	for (UIImage* image in m_listImageData) {
		CGSize imageSize = image.size;
		CGSize viewSize;
		CGRect frame;
		if (isLand) {
			viewSize = CGSizeMake(kWidthLand, kHeightLand);	
			frame = CGRectMake(0, 44, 1024, 660);
		}
		else {
			viewSize = CGSizeMake(kWidthPort, kHeightPort);	
			frame = CGRectMake(0, 44, 768, 916);
		}			
		float hRate = viewSize.width  / imageSize.width;
		float vRate = viewSize.height / imageSize.height;
		float ratio = ( hRate > vRate ) ? vRate : hRate;
		
		CGRect rect = CGRectMake( 0, 0, imageSize.width * ratio, imageSize.height * ratio );
		UIGraphicsBeginImageContext( rect.size );
		[image drawInRect:rect];
		
		UIImage* resizeImage = UIGraphicsGetImageFromCurrentImageContext();
		UIImageView* image_view = [[UIImageView alloc] initWithImage:resizeImage];
		
		image_view.frame = getAspectRect( rect, frame);	
		UIGraphicsEndImageContext();
		[m_listImageView addObject:image_view];				
		[image_view release];
	}	
}


- (void) addImageViewToScrollView: (BOOL) isLand
{				
	m_scrollView.pagingEnabled = YES;
	for (UIView* view in [m_scrollView subviews]) {
		[view removeFromSuperview];
	}		
	CGRect rect;
	if (isLand) {
		[m_scrollView setContentSize: CGSizeMake(kWidthLand* [m_listImageView count], kHeightLand)];
		rect = CGRectMake(0.0, 0.0, kWidthLand, kHeightLand);
	}
	else {
		[m_scrollView setContentSize: CGSizeMake(kWidthPort* [m_listImageView count], kHeightPort)];
		rect = CGRectMake(0.0, 0.0, kWidthPort, kHeightPort);
	}

	for (int i = 0; i < [m_listImageView count]; i++) {	
		UIImageView* imageView = [m_listImageView objectAtIndex:i];
		if (isLand) {
			rect.origin.x = i*kWidthLand;

		}
		else {
			rect.origin.x = i*kWidthPort;
		}
		MyScrollView* scrollImage = [[MyScrollView alloc] initWithFrame:rect];	
		[scrollImage addSubview:imageView];
		scrollImage.maximumZoomScale = 3.0;
		scrollImage.minimumZoomScale = 0.75;
		scrollImage.tag = i;
		scrollImage.delegate = scrollImage;
		[m_scrollView addSubview:scrollImage];
		[scrollImage release];

	}		

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	m_isSlideshow = [OrderOnlineViewController Shared].m_isSlideShow;
	if (m_isSlideshow) {
		[m_barButonSlide setTitle:@"Stop Slideshow"];
	}
	else {
		[m_barButonSlide setTitle:@"Start Slideshow"];
	}
	
	UIInterfaceOrientation orie = [OrderOnlineViewController Shared].m_DeviceOrie;  	    
    BOOL isLand = isDeviceLandScape(orie);
	
	[self loadImageView: isLand];
	[self addImageViewToScrollView:isLand];
	[self setTitlePage];
	[self.view bringSubviewToFront:m_viewInfo];
	[self setViewInfo: [self getPageCurrent]];
	if (m_isSlideshow) {
		[self setHideInfoFood:NO];
	}
	else {
		[self setHideInfoFood:YES];
	}

}

- (void) setFrame
{
	UIInterfaceOrientation orie = [OrderOnlineViewController Shared].m_DeviceOrie;  	    
    BOOL isLand = isDeviceLandScape(orie);	
	[self loadImageView: isLand];
	[self addImageViewToScrollView:isLand];
	
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
	return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void) setTitlePage
{
	int numImage = [self getPageCurrent] + 1;
	[m_naviBar.topItem setTitle:[NSString stringWithFormat:@"%d of %d", numImage, [m_listImageView count]]];
	
}
- (void) setViewInfo: (int) pageCurrent
{	
	Food* food = [m_listData objectAtIndex:pageCurrent];
	[m_lblName setText:food.m_title];
	[m_lblPrice setText:[NSString stringWithFormat:@"%f", food.m_price]];
	[m_lblDiscount setText: food.m_discount];	

	[self.view bringSubviewToFront:m_lblName];
	[self.view bringSubviewToFront:m_lblPrice];
	[self.view bringSubviewToFront:m_lblDiscount];
	[self.view bringSubviewToFront:m_titleName];
	[self.view bringSubviewToFront:m_titlePrice];
	[self.view bringSubviewToFront:m_titleDiscount];	
	[self.view bringSubviewToFront:m_toolBar];
}

- (void) setHideInfoFood: (BOOL) isHide
{	
	[m_lblName setHidden:isHide];
	[m_lblPrice setHidden:isHide];
	[m_lblDiscount setHidden:isHide];
	[m_titleName setHidden:isHide];
	[m_titlePrice setHidden:isHide];
	[m_titleDiscount setHidden:isHide];
	[m_viewInfo setHidden:isHide];				
}

- (void)dealloc {
    [super dealloc];
	[m_scrollView release];
	[m_listImageData release];
	[m_listImageView release];
	[m_naviBar release];	
	[m_barAdd release];
	[m_barButonSlide release];
	[m_toolBar release];
	[m_viewInfo release];
	[m_lblName release];
	[m_lblPrice release];
	[m_lblDiscount release];
	[m_titleName release];
	[m_titlePrice release];
	[m_titleDiscount release];
	
}

- (int) getPageCurrent
{
	CGFloat pageWidth = m_scrollView.frame.size.width;
    int pageCurrent = floor((m_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	return pageCurrent;
}

- (void) changePage:(int)pageNo
{
	CGRect frame = m_scrollView.frame;
	UIInterfaceOrientation orie = [OrderOnlineViewController Shared].m_DeviceOrie;  	    
    BOOL isLand = isDeviceLandScape(orie);
	if (isLand) {
		frame.origin.x = kWidthLand * pageNo;
	}
	else {
		frame.origin.x = kWidthPort * pageNo;
	}
	[m_scrollView scrollRectToVisible:frame animated:NO];	
	
}

- (void) changeBackHome: (id) sender
{
	[OrderOnlineViewController Shared].m_isSlideShow = NO;
	[[OrderOnlineViewController Shared] changeHomeView:YES];
}

- (void) setAutoScroll: (id) sender
{
	m_isSlideshow = !m_isSlideshow;
	[OrderOnlineViewController Shared].m_isSlideShow = m_isSlideshow;
	if (m_isSlideshow) {
		[m_barButonSlide setTitle:@"Stop Slideshow"];
	}
	else {
		[m_barButonSlide setTitle:@"Start Slideshow"];
	}
	
	[self slideShow: m_isSlideshow];

}

- (void) slideShow: (BOOL) isSlideshow
{
	
	if (isSlideshow) {
		
		m_timerScroll = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
		[self setHideInfoFood:NO];
	}
	else {
		[m_timerScroll invalidate];
		[self setHideInfoFood:YES];
	}
}
#pragma mark -
#pragma mark Scroll Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (scrollView == m_scrollView) {
		float scrollWidth = m_scrollView.frame.size.width;
		m_currImageView = floor((m_scrollView.contentOffset.x-scrollWidth/2)/scrollWidth)+1;
		[self setTitlePage];
		[self setViewInfo: m_currImageView];
	}
}
- (void)onTimer {
	UIInterfaceOrientation orie = [OrderOnlineViewController Shared].m_DeviceOrie;  	    
    BOOL isLand = isDeviceLandScape(orie);
	CGRect rect = m_scrollView.frame;
	if (isLand)
	{
		rect.origin.x = kWidthLand* m_currImageView;
	}
	else {
		rect.origin.x = kWidthPort* m_currImageView;
	}
	
	[m_scrollView scrollRectToVisible:rect animated:YES];
	[self setTitlePage];
	[self setViewInfo: m_currImageView];
	m_currImageView++;
	if(m_currImageView > [m_listImageView count] - 1){
		m_currImageView = 0;
	}
	
}

- (void) addFoodToOrder: (id) sender
{
	int indexCurrent = [self getPageCurrent];
	Food* food = [m_listData objectAtIndex:indexCurrent];
	//SAFE_RELEASE(popoverViewController)
	//SAFE_RELEASE(popover)
	if (popoverViewController == nil) {
		self.m_popoverViewController = [[[PopoverViewController alloc] initWithStyle:UITableViewStylePlain] autorelease];
		[popoverViewController setFrame:food]; 
		popoverViewController.m_delegate = self;
		self.m_popover = [[[UIPopoverController alloc] initWithContentViewController:popoverViewController] autorelease];   
	}
	[popoverViewController setObjectFood:food];                  
	[self.m_popover presentPopoverFromRect:CGRectMake(0 , 0, self.m_toolBar.frame.size.width, self.m_toolBar.frame.size.height) inView:self.m_toolBar permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; 
}

- (void) buttonCancel
{
	[self.m_popover dismissPopoverAnimated:YES];
    [self.m_popover setDelegate:nil]; 
}

- (void) seeInfoFood: (id) sender
{
	m_isInfoHide = !m_isInfoHide;
	[self setHideInfoFood:m_isInfoHide];
}

- (void) changeToOrder: (id) sender
{
	[[OrderOnlineViewController Shared] changeOrderView:YES];
}

@end

@implementation MyScrollView
@synthesize m_scrollImage;

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
	m_scrollImage = [[self subviews] objectAtIndex:0]; 
	return m_scrollImage;
}

@end

